import sys
import os
import traceback


class Cmd:
    def __init__(self, paths=["commands"]):
        # 命令文件模块路径
        self.paths = paths
        # 将要执行的命令
        self.command = None
        # 元祖参数
        self.args = []
        # 字典参数
        self.keyword = {}
        # 命令词典
        self.commands = {}

    # 运行
    def run(self):
        self.analysisCmd()
        self.loadCommands()
        if self.commands.__contains__(self.command):
            self.commands[self.command]().run(*self.args,**self.keyword)
        else:
            print("命令" + self.command + "不存在,请确认后再试")

    # 解析参数
    def analysisCmd(self):
        self.command = sys.argv[1]
        for i, v in enumerate(sys.argv):
            if "=" in v and "--" in v:
                sd = v.split("=", 1)
                self.keyword[sd[0].replace("--", "")] = sd[1]
            else:
                self.args.append(v)

    # 加载命令模块
    def loadCommands(self):
        for path in self.paths:
            m = __import__(path, fromlist=["commands"])
            for c in m.commands:
                if self.commands.__contains__(c.name):
                    print("命令" + c.name + "已存在,请确认后再试")
                else:
                    self.commands[c.name] = c